// 采空区地质封存选址指标数据
const indicators = [
    {
        id: 'temperature_gradient',
        name: '地温梯度(℃/100m)',
        category: '工程地质条件',
        criteria: {
            suitable: { min: null, max: 2, description: '＜ 2' },
            general: { min: 2, max: 3, description: '［2，3］' },
            unsuitable: { min: 3, max: null, description: '＞ 3' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'number',
        unit: '℃/100m'
    },
    {
        id: 'cover_rock_type',
        name: '盖层岩性',
        category: '工程地质条件',
        criteria: {
            suitable: { description: '蒸发岩类' },
            general: { description: '泥质岩类' },
            unsuitable: { description: '页岩和致密灰岩' }
        },
        improvement: '打孔注浆，改变它的孔隙度...',
        inputType: 'select',
        options: ['蒸发岩类', '泥质岩类', '页岩和致密灰岩']
    },
    {
        id: 'cover_fracture',
        name: '盖层断裂发育',
        category: '工程地质条件',
        criteria: {
            suitable: { description: '有限的断层和裂缝，大的泥岩' },
            general: { description: '中等断层中等裂缝' },
            unsuitable: { description: '大断层大裂缝' }
        },
        improvement: '采用定向注浆或化学封堵方式...',
        inputType: 'select',
        options: ['有限的断层和裂缝，大的泥岩', '中等断层中等裂缝', '大断层大裂缝']
    },
    {
        id: 'reservoir_rock_type',
        name: '储层岩性',
        category: '工程地质条件',
        criteria: {
            suitable: { description: '碎屑岩' },
            general: { description: '碎屑岩、碳酸盐岩混合' },
            unsuitable: { description: '碳酸盐岩' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'select',
        options: ['碎屑岩', '碎屑岩、碳酸盐岩混合', '碳酸盐岩']
    },
    {
        id: 'reservoir_facies',
        name: '储层沉积相',
        category: '工程地质条件',
        criteria: {
            suitable: { description: '河流、三角洲' },
            general: { description: '浊流、冲积扇' },
            unsuitable: { description: '滩坝与生物礁' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'select',
        options: ['河流、三角洲', '浊流、冲积扇', '滩坝与生物礁']
    },
    {
        id: 'pressure_coefficient',
        name: '储层压力系数',
        category: '工程地质条件',
        criteria: {
            suitable: { min: null, max: 0.9, description: '＜0.9' },
            general: { min: 0.9, max: 1.1, description: '［0.9，1.1］' },
            unsuitable: { min: 1.1, max: null, description: '＞ 1.1' }
        },
        improvement: '通过抽水或采气，减少孔隙流体体积，压力系数下降',
        inputType: 'number',
        unit: ''
    },
    {
        id: 'coal_depth',
        name: '煤层埋深 (m)',
        category: '封存潜力条件',
        criteria: {
            suitable: { min: 1500, max: null, description: '＞1500' },
            general: { min: 1200, max: 1500, description: '［1200，1500］' },
            unsuitable: { min: 1000, max: 1200, description: '［1000, 1200)' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'number',
        unit: 'm'
    },
    {
        id: 'cover_thickness',
        name: '盖层厚度 (m)',
        category: '封存潜力条件',
        criteria: {
            suitable: { min: 100, max: null, description: '＞100' },
            general: { min: 50, max: 100, description: '［50，100］' },
            unsuitable: { min: null, max: 50, description: '＜ 50' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'number',
        unit: 'm'
    },
    {
        id: 'cover_permeability',
        name: '盖层渗透率(×10⁻³μm²)',
        category: '封存潜力条件',
        criteria: {
            suitable: { min: null, max: 0.01, description: '＜ 0.01' },
            general: { min: 0.01, max: 1, description: '［0.01，1］' },
            unsuitable: { min: 1, max: null, description: '＞1' }
        },
        improvement: '通过高压注入反应性流体或胶结剂...',
        inputType: 'number',
        unit: '×10⁻³μm²'
    },
    {
        id: 'cover_stability',
        name: '盖层力学稳定性',
        category: '封存潜力条件',
        criteria: {
            suitable: { description: '稳定' },
            general: { description: '较稳定' },
            unsuitable: { description: '不稳定' }
        },
        improvement: '改变盖层力学性质，注浆固化...',
        inputType: 'select',
        options: ['稳定', '较稳定', '不稳定']
    },
    {
        id: 'cover_continuity',
        name: '盖层分布连续性',
        category: '封存潜力条件',
        criteria: {
            suitable: { description: '分布连续，具区域性' },
            general: { description: '分布基本连续' },
            unsuitable: { description: '分布不连续，局限' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'select',
        options: ['分布连续，具区域性', '分布基本连续', '分布不连续，局限']
    },
    {
        id: 'cover_gas_index',
        name: '盖层封气指数 (m)',
        category: '封存潜力条件',
        criteria: {
            suitable: { min: 200, max: null, description: '＞200' },
            general: { min: 100, max: 200, description: '［100，200］' },
            unsuitable: { min: null, max: 100, description: '＜ 100' }
        },
        improvement: '减小注入时超临界二氧化碳的压力...',
        inputType: 'number',
        unit: 'm'
    },
    {
        id: 'cover_count',
        name: '盖层数量',
        category: '封存潜力条件',
        criteria: {
            suitable: { description: '多套，质量好' },
            general: { description: '多套，质量一般' },
            unsuitable: { description: '一套' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'select',
        options: ['多套，质量好', '多套，质量一般', '一套']
    },
    {
        id: 'reservoir_thickness',
        name: '储层厚度(主力储层) (m)',
        category: '封存潜力条件',
        criteria: {
            suitable: { min: 80, max: null, description: '＞80' },
            general: { min: 30, max: 80, description: '［30，80］' },
            unsuitable: { min: null, max: 30, description: '＜ 30' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'number',
        unit: 'm'
    },
    {
        id: 'reservoir_rock_type_porosity',
        name: '储层孔隙度(%)',
        category: '封存潜力条件',
        criteria: {
            suitable: { description: '砂岩＞15% 或 碳酸盐岩＞12%' },
            general: { description: '砂岩10-15% 或 碳酸盐岩4-12%' },
            unsuitable: { description: '砂岩＜10% 或 碳酸盐岩＜4%' }
        },
        improvement: '增加孔隙度的方法：对其进行水压致裂，周期性加压与卸载，增大其孔隙度；或者参考页岩的水化作用，对储层进行加工。',
        inputType: 'composite',
        fields: [
            { id: 'rock_type', name: '储层岩性', type: 'select', options: ['砂岩', '碳酸盐岩'] },
            { id: 'porosity', name: '孔隙度', type: 'number', unit: '%' }
        ]
    },
    {
        id: 'reservoir_rock_type_permeability',
        name: '储层渗透率(×10⁻³μm²)',
        category: '封存潜力条件',
        criteria: {
            suitable: { description: '砂岩＞50 或 碳酸盐岩＞10' },
            general: { description: '砂岩10-50 或 碳酸盐岩5-10' },
            unsuitable: { description: '砂岩＜10 或 碳酸盐岩＜5' }
        },
        improvement: '与上面相似',
        inputType: 'composite',
        fields: [
            { id: 'rock_type', name: '储层岩性', type: 'select', options: ['砂岩', '碳酸盐岩'] },
            { id: 'permeability', name: '渗透率', type: 'number', unit: '×10⁻³μm²' }
        ]
    },
    {
        id: 'permeability_variation',
        name: '储层渗透率变异系数',
        category: '封存潜力条件',
        criteria: {
            suitable: { min: null, max: 0.5, description: '＜0.5' },
            general: { min: 0.5, max: 0.6, description: '［0.5，0.6］' },
            unsuitable: { min: 0.6, max: null, description: '＞ 0.6' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'number',
        unit: ''
    },
    {
        id: 'reservoir_continuity',
        name: '储层分布连续性 (m)',
        category: '封存潜力条件',
        criteria: {
            suitable: { min: 2000, max: null, description: '＞2000' },
            general: { min: 600, max: 2000, description: '［600，2000］' },
            unsuitable: { min: null, max: 600, description: '＜ 600' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'number',
        unit: 'm'
    },
    {
        id: 'injection_capacity',
        name: '储层数量注入能力(主力储层) (m³)',
        category: '封存潜力条件',
        criteria: {
            suitable: { min: 1e-13, max: null, description: '＞10⁻¹³' },
            general: { min: 1e-15, max: 1e-13, description: '［10⁻¹⁵，10⁻¹³］' },
            unsuitable: { min: null, max: 1e-15, description: '＜ 10⁻¹⁵' }
        },
        improvement: '产水降低地层压力...',
        inputType: 'number',
        unit: 'm³'
    },
    {
        id: 'reservoir_cover_count',
        name: '储盖组合数量',
        category: '封存潜力条件',
        criteria: {
            suitable: { description: '多套' },
            general: { description: '可能存在' },
            unsuitable: { description: '无' }
        },
        improvement: '无法修改，建议直接放弃；',
        inputType: 'select',
        options: ['多套', '可能存在', '无']
    }
];

let currentIndex = 0;
let userResponses = {};

// 初始化应用
function initApp() {
    // 设置导航菜单事件
    setupNavigation();
    
    // 初始隐藏表单容器
    document.getElementById('form-container').style.display = 'none';
    document.querySelector('.progress-container').style.display = 'none';
    document.querySelector('.conclusion-section').style.display = 'none';
    document.querySelector('.navigation-buttons').style.display = 'none';
    
    // 设置查询按钮事件
    document.getElementById('query-btn').addEventListener('click', function() {
        const selectedProject = document.getElementById('project-select').value;
        if (selectedProject) {
            // 显示所有评估相关的元素
            document.getElementById('form-container').style.display = 'block';
            document.querySelector('.progress-container').style.display = 'block';
            document.querySelector('.conclusion-section').style.display = 'block';
            document.querySelector('.navigation-buttons').style.display = 'flex';
            
            renderCurrentIndicator();
            updateProgress();
            setupEventListeners();
        } else {
            alert('请选择巷道名称');
        }
    });
}

// 设置导航菜单功能
function setupNavigation() {
    const navItems = document.querySelectorAll('.nav-menu li');
    
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            const menuText = this.textContent;
            handleNavigation(menuText);
        });
    });
}

// 处理导航菜单点击
function handleNavigation(menuText) {
    // 更新激活状态
    const navItems = document.querySelectorAll('.nav-menu li');
    navItems.forEach(item => {
        if (item.textContent === menuText) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });
    
    switch(menuText) {
        case '工程管理':
            alert('工程管理功能：可以管理多个采空区封存项目\n\n功能包括：\n• 新建工程项目\n• 编辑项目信息\n• 删除项目\n• 项目状态管理');
            break;
        case '数值模拟分析':
            alert('数值模拟分析功能：进行地质力学和流体动力学模拟\n\n模拟类型：\n• 应力场分析\n• 渗流场模拟\n• 温度场分析\n• 多场耦合分析');
            break;
        case '支护参数设计':
            alert('支护参数设计功能：根据评估结果设计支护方案\n\n设计内容：\n• 锚杆支护参数\n• 喷射混凝土参数\n• 注浆加固方案\n• 监测系统设计');
            break;
        case '数据查询':
            // 刷新页面回到初始状态
            alert('数据查询功能：查看历史评估数据和结果\n\n正在加载数据查询界面...');
            location.reload();
            break;
        case '退出系统':
            if (confirm('确定要退出采空区地质封存选址打分系统吗？')) {
                alert('系统已安全退出，感谢使用！');
                // 在实际应用中这里可以跳转到登录页或关闭窗口
            }
            break;
        default:
            alert('功能开发中，敬请期待');
    }
}

// 渲染当前指标表单
function renderCurrentIndicator() {
    const form = document.getElementById('assessment-form');
    const indicator = indicators[currentIndex];
    
    form.innerHTML = `
        <div class="form-group">
            <h3>${indicator.category} - ${indicator.name}</h3>
            <p>评价标准: 
                适宜: ${indicator.criteria.suitable.description} | 
                一般: ${indicator.criteria.general.description} | 
                不适宜: ${indicator.criteria.unsuitable.description}
            </p>
            <label for="${indicator.id}">请输入${indicator.name}${indicator.unit ? ` (${indicator.unit})` : ''}:</label>
            ${createInputField(indicator)}
        </div>
    `;
}

// 创建输入字段
function createInputField(indicator) {
    if (indicator.inputType === 'select') {
        return `
            <select id="${indicator.id}" name="${indicator.id}" required>
                <option value="">请选择</option>
                ${indicator.options.map(opt => `<option value="${opt}">${opt}</option>`).join('')}
            </select>
        `;
    } else if (indicator.inputType === 'composite') {
        return indicator.fields.map(field => `
            <div style="margin-bottom: 10px;">
                <label for="${indicator.id}_${field.id}">${field.name}${field.unit ? ` (${field.unit})` : ''}:</label>
                ${field.type === 'select' ? `
                    <select id="${indicator.id}_${field.id}" name="${indicator.id}_${field.id}" required>
                        <option value="">请选择</option>
                        ${field.options.map(opt => `<option value="${opt}">${opt}</option>`).join('')}
                    </select>
                ` : `
                    <input type="number" id="${indicator.id}_${field.id}" name="${indicator.id}_${field.id}" step="any" required>
                `}
            </div>
        `).join('');
    } else {
        return `<input type="number" id="${indicator.id}" name="${indicator.id}" step="any" required>`;
    }
}

// 设置事件监听器
function setupEventListeners() {
    document.getElementById('prev-btn').addEventListener('click', goToPrevious);
    document.getElementById('next-btn').addEventListener('click', goToNext);
    document.getElementById('submit-btn').addEventListener('click', submitAssessment);
    document.getElementById('restart-btn').addEventListener('click', restartAssessment);
    
    // 显示界面元素
    document.getElementById('form-container').style.display = 'block';
    document.querySelector('.progress-container').style.display = 'block';
    document.querySelector('.conclusion-section').style.display = 'block';
    document.querySelector('.navigation-buttons').style.display = 'flex';
}

// 更新进度
function updateProgress() {
    const progressFill = document.getElementById('progress-fill');
    const progressText = document.getElementById('progress-text');
    const progress = ((currentIndex + 1) / indicators.length) * 100;
    
    progressFill.style.width = `${progress}%`;
    progressText.textContent = `进度: ${currentIndex + 1}/${indicators.length}`;
    
    // 更新按钮状态
    document.getElementById('prev-btn').disabled = currentIndex === 0;
    document.getElementById('next-btn').style.display = currentIndex < indicators.length - 1 ? 'block' : 'none';
    document.getElementById('submit-btn').style.display = currentIndex === indicators.length - 1 ? 'block' : 'none';
}

// 导航函数
function goToPrevious() {
    if (currentIndex > 0) {
        saveCurrentResponse();
        currentIndex--;
        renderCurrentIndicator();
        updateProgress();
    }
}

function goToNext() {
    if (validateCurrentInput()) {
        saveCurrentResponse();
        currentIndex++;
        renderCurrentIndicator();
        updateProgress();
    }
}

// 验证当前输入
function validateCurrentInput() {
    const indicator = indicators[currentIndex];
    
    if (indicator.inputType === 'composite') {
        // 验证所有复合字段
        for (const field of indicator.fields) {
            const input = document.getElementById(`${indicator.id}_${field.id}`);
            if (!input.value) {
                alert(`请填写${field.name}`);
                return false;
            }
        }
        return true;
    } else {
        const input = document.getElementById(indicator.id);
        if (!input.value) {
            alert('请填写当前指标数据');
            return false;
        }
        return true;
    }
}

// 保存当前响应
function saveCurrentResponse() {
    const indicator = indicators[currentIndex];
    
    if (indicator.inputType === 'composite') {
        userResponses[indicator.id] = {};
        for (const field of indicator.fields) {
            const input = document.getElementById(`${indicator.id}_${field.id}`);
            userResponses[indicator.id][field.id] = input.value;
        }
    } else {
        const input = document.getElementById(indicator.id);
        userResponses[indicator.id] = input.value;
    }
}

// 提交评估
function submitAssessment() {
    if (validateCurrentInput()) {
        saveCurrentResponse();
        calculateAndDisplayResults();
    }
}

// 计算并显示结果
function calculateAndDisplayResults() {
    const scores = calculateScores();
    const totalScore = calculateTotalScore(scores);
    const recommendation = getRecommendation(totalScore, scores);
    
    displayResults(totalScore, recommendation, scores);
}

// 计算各指标得分
function calculateScores() {
    return indicators.map(indicator => {
        const value = userResponses[indicator.id];
        const score = calculateIndicatorScore(indicator, value);
        return {
            indicator: indicator.name,
            score: score,
            improvement: indicator.improvement,
            category: indicator.category
        };
    });
}

// 计算单个指标得分
function calculateIndicatorScore(indicator, value) {
    const criteria = indicator.criteria;
    
    // 判断适宜等级
    let level;
    if (indicator.inputType === 'select') {
        if (value === criteria.suitable.description) level = 'suitable';
        else if (value === criteria.general.description) level = 'general';
        else level = 'unsuitable';
    } else if (indicator.inputType === 'composite') {
        // 处理复合字段
        const rockType = value.rock_type;
        let numValue;
        
        if (indicator.name.includes('孔隙度')) {
            numValue = parseFloat(value.porosity);
            if (rockType === '砂岩') {
                if (numValue > 15) level = 'suitable';
                else if (numValue >= 10 && numValue <= 15) level = 'general';
                else level = 'unsuitable';
            } else { // 碳酸盐岩
                if (numValue > 12) level = 'suitable';
                else if (numValue >= 4 && numValue <= 12) level = 'general';
                else level = 'unsuitable';
            }
        } else if (indicator.name.includes('渗透率')) {
            numValue = parseFloat(value.permeability);
            if (rockType === '砂岩') {
                if (numValue > 50) level = 'suitable';
                else if (numValue >= 10 && numValue <= 50) level = 'general';
                else level = 'unsuitable';
            } else { // 碳酸盐岩
                if (numValue > 10) level = 'suitable';
                else if (numValue >= 5 && numValue <= 10) level = 'general';
                else level = 'unsuitable';
            }
        }
    } else {
        const numValue = parseFloat(value);
        if ((criteria.suitable.min !== null && numValue > criteria.suitable.min) || 
            (criteria.suitable.max !== null && numValue < criteria.suitable.max)) {
            level = 'suitable';
        } else if ((criteria.general.min !== null && criteria.general.max !== null && 
                   numValue >= criteria.general.min && numValue <= criteria.general.max)) {
            level = 'general';
        } else {
            level = 'unsuitable';
        }
    }
    
    // 计算得分（严格按照要求）
    switch (level) {
        case 'suitable':
            return Math.random() * 20 + 80; // (80,100) 开区间随机
        case 'general':
            if (indicator.inputType === 'select' || indicator.inputType === 'composite') {
                return Math.random() * 20 + 60; // [60,80] 闭区间随机
            } else {
                // 数字区间按比例计算
                const numValue = indicator.inputType === 'composite' ? 
                    parseFloat(value[Object.keys(value).find(k => k !== 'rock_type')]) : 
                    parseFloat(value);
                const range = criteria.general.max - criteria.general.min;
                const position = (numValue - criteria.general.min) / range;
                return 60 + position * 20; // [60,80] 按比例
            }
        case 'unsuitable':
            return Math.random() * 20 + 40; // (40,60) 开区间随机
    }
}

// 计算总分
function calculateTotalScore(scores) {
    const weight = 100 / scores.length; // 动态计算权重
    return scores.reduce((total, item) => total + item.score * (weight / 100), 0);
}

// 获取建议
function getRecommendation(totalScore, scores) {
    if (totalScore < 60) {
        return {
            level: '三级（差）',
            suggestion: '不适宜封存二氧化碳，建议直接放弃',
            improvements: []
        };
    } else if (totalScore >= 80) {
        return {
            level: '一级（优）',
            suggestion: '各项指标均适宜，无需改进',
            improvements: []
        };
    } else {
        const lowScores = scores.filter(item => item.score < 60);
        if (lowScores.length > 0) {
            return {
                level: '二级（良）',
                suggestion: '需要改进所有低于60分的指标',
                improvements: lowScores
            };
        } else {
            const minScore = Math.min(...scores.map(item => item.score));
            const minScoreItem = scores.find(item => item.score === minScore);
            return {
                level: '二级（良）',
                suggestion: '需要改进最低分指标',
                improvements: [minScoreItem]
            };
        }
    }
}

// 显示结果
function displayResults(totalScore, recommendation, scores) {
    document.getElementById('form-container').style.display = 'none';
    document.getElementById('prev-btn').style.display = 'none';
    document.getElementById('next-btn').style.display = 'none';
    document.getElementById('submit-btn').style.display = 'none';
    document.getElementById('restart-btn').style.display = 'inline-block';
    
    // 更新分析结论
    let stabilityClass, supportSuggestion;
    
    if (totalScore < 60) {
        stabilityClass = '三级（差）- 不适宜封存';
        supportSuggestion = '建议直接放弃该选址';
    } else if (totalScore >= 80) {
        stabilityClass = '一级（优）- 适宜封存';
        supportSuggestion = '各项指标均适宜，无需改进';
    } else {
        stabilityClass = '二级（良）- 需要改进';
        supportSuggestion = recommendation.improvements.length > 0 ? 
            `需要改进${recommendation.improvements.length}个指标` : 
            '需要改进最低分指标';
    }
    
    document.getElementById('stability-class').textContent = stabilityClass;
    document.getElementById('support-suggestion').textContent = supportSuggestion;
    
    // 显示改进建议
    const improvements = recommendation.improvements.map(item => 
        `${item.indicator}: ${item.score.toFixed(2)}分 - ${item.improvement}`
    ).join('\n');
    
    if (improvements) {
        alert(`评估完成！总分: ${totalScore.toFixed(2)}分\n\n改进建议:\n${improvements}`);
    } else {
        alert(`评估完成！总分: ${totalScore.toFixed(2)}分\n\n${supportSuggestion}`);
    }
}

// 重新开始评估
function restartAssessment() {
    currentIndex = 0;
    userResponses = {};
    document.getElementById('form-container').style.display = 'block';
    document.getElementById('prev-btn').style.display = 'inline-block';
    document.getElementById('next-btn').style.display = 'inline-block';
    document.getElementById('submit-btn').style.display = 'none';
    document.getElementById('restart-btn').style.display = 'none';
    
    // 重置分析结论
    document.getElementById('stability-class').textContent = '待评估';
    document.getElementById('support-suggestion').textContent = '待评估';
    
    renderCurrentIndicator();
    updateProgress();
}

// 初始化应用
document.addEventListener('DOMContentLoaded', initApp);